<?php


namespace Faed\LaravelAuthDoc\middleware;
use Closure;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RecordReturn
{
    public function handle($request, Closure $next)
    {
        /**@var $request Request **/
        $resource = $next($request);
        if (config('authdoc.is_cache')){
            $content = $resource->getContent();
            //异常等等信息不记录 只记录正常json
            if (!is_null(json_decode($content))){
                try {
                    $recordReturn = Cache::get('record-return',[]);
                    $recordReturn = array_merge($recordReturn,[join('|',$request->route()->methods()).'_'.$request->route()->uri()=>$content]);
                    /**@var $resource JsonResponse **/
                    Cache::set('record-return',$recordReturn);
                }catch (Exception $exception){
                    Log::error("保存返回缓存:".$exception->getMessage());
                }
            }
        }

        return $resource;
    }
}
